#include <iostream>
#include <memory>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <string>
#include <unistd.h>
#include <functional>

#include "Log.hpp"


int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        LOG(INFO,"./tcpclient serverip serverport\n");
        exit(2);
    }

    //创建套接字
    int sockfd = ::socket(AF_INET,SOCK_STREAM,0);
    if(sockfd < 0)
    {
        LOG(FATAL,"client socket creat error\n");
        exit(2);
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    
    struct sockaddr_in server;
    socklen_t len = sizeof(server);
    memset(&server,0,len);
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    ::inet_pton(AF_INET,serverip.c_str(),&server.sin_addr);
    
    //connect
    int n = ::connect(sockfd, (struct sockaddr *)&server, sizeof(server));
    if (n < 0)
    {
        std::cerr << "connect socket error" << std::endl;
        exit(2);
    }
    
    while(true)
    {
        std::string message;
        std::cout << "Enter# ";
        std::cin >> message;    

        //write
        write(sockfd,message.c_str(),message.size());

        //read
        char buff[1024];
        n = read(sockfd,buff,sizeof(buff)-1);
        if(n > 0)
        {
            buff[n-1] = 0;
            std::cout << buff<<std::endl;
        }
        else
        {
            break;
        }
    }
    ::close(sockfd);

    return 0;
}